package com.example.mcdonaldapplication.activity

import android.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mcdonaldapplication.databinding.ActivityChoseAddressBinding
import com.example.mcdonaldapplication.info.AddressAdapter
import com.example.mcdonaldapplication.info.ServerIP
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread

class ChoseAddressActivity : AppCompatActivity(),View.OnClickListener {
    private lateinit var binding: ActivityChoseAddressBinding
    private val serverIP = ServerIP.getIp()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityChoseAddressBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()
        getAddress()
        binding.btnAddAddress.setOnClickListener(this)
        binding.btnAddAddressBottom.setOnClickListener(this)
    }

    private fun getAddress(){
        thread {
            val prefs = getSharedPreferences("user", MODE_PRIVATE)
            val uid = prefs.getInt("uid", 0)
            //post方式提交的数据
            val formBody: FormBody = FormBody.Builder()
                .add("id", uid.toString())
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIP}/user/queryAddress")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJsonAddress(responseData)
        }
    }

    private fun parseJsonAddress(jsonData: String) {
        val prefs = getSharedPreferences("user", MODE_PRIVATE)
        val username = prefs.getString("username", "")!!
        val phone = prefs.getString("mobile", "")!!
        val jsonObject = JSONObject(jsonData)
        val data = jsonObject.getString("data")
        val newData = data.drop(1).dropLast(1).replace("\"", "")
        val addressList = newData.split(",")
        if(data == "null"){
            runOnUiThread {
                binding.btnAddAddress.visibility = View.VISIBLE
                binding.tvNoneAdd.visibility = View.VISIBLE
                binding.btnAddAddressBottom.visibility = View.GONE
                binding.recyclerView.visibility = View.GONE
            }
        }else{
            runOnUiThread {
                binding.recyclerView.visibility = View.VISIBLE
                binding.btnAddAddressBottom.visibility = View.VISIBLE
                binding.btnAddAddress.visibility = View.GONE
                binding.tvNoneAdd.visibility = View.GONE
                val layoutManager = LinearLayoutManager(this)
                binding.recyclerView.layoutManager = layoutManager
                val recycleAdapter = AddressAdapter(addressList, username, phone, this)
                binding.recyclerView.adapter = recycleAdapter
            }
        }
    }

    private fun addAddress(address:String){
        thread {
            val prefs = getSharedPreferences("user", MODE_PRIVATE)
            val uid = prefs.getInt("uid", 0)
            //post方式提交的数据
            val formBody: FormBody = FormBody.Builder()
                .add("id", uid.toString())
                .add("address", address)
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIP}/user/addAddress")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJsonAddAddress(responseData)
        }
    }

    private fun parseJsonAddAddress(jsonData: String) {
        val jsonObject = JSONObject(jsonData)
        val success = jsonObject.getString("success")
        if(success == "true"){
            getAddress()
        }
    }

    override fun onResume() {
        super.onResume()
        getAddress()
    }

    override fun onClick(v: View?) {
        val et = EditText(this)
        when (v?.id) {
            com.example.mcdonaldapplication.R.id.btnAddAddress ->{
                AlertDialog.Builder(this).apply {
                    setTitle("请输入地址")
                    setView(et)
                    setCancelable(false)
                    setPositiveButton("添加") { _, _ ->
                        val address = et.text.toString()
                        addAddress(address)
                    }
                    setNegativeButton("取消") { _, _ ->
                    }
                    show()
                }
            }
            com.example.mcdonaldapplication.R.id.btnAddAddressBottom -> {
                AlertDialog.Builder(this).apply {
                    setTitle("请输入地址")
                    setView(et)
                    setCancelable(false)
                    setPositiveButton("添加") { _, _ ->
                        val address = ",${et.text}"
                        addAddress(address)
                    }
                    setNegativeButton("取消") { _, _ ->
                    }
                    show()
                }
            }
        }
    }
}